import json
import queue
from socket import *
import threading
import logging

logger = logging.getLogger(__file__)


class UDPListener:
    def __init__(self):
        self.s: socket
        self.msg_queue = queue.Queue()
        self._thread = threading.Thread(target=self._listen)
        self._thread.daemon = True

    def start(self):
        self._thread.start()

    def _listen(self):
        # IP 地址为空表示接收任何网段的广播消息
        address = ("", 10130)

        # 创建 UDP 套接字
        self.s = socket(AF_INET, SOCK_DGRAM)

        # 设置套接字属性，允许广播
        self.s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

        # 绑定本地 IP 地址和端口
        self.s.bind(address)
        print("Waiting to receive...")

        # 接收消息
        while 1:
            data, address = self.s.recvfrom(1024)
            try:
                json_data = json.loads(data)
                self.msg_queue.put(json_data)
            except json.JSONDecodeError:
                logger.error(
                    f"JSONDecodeError OCCURRED: {address[0]}:{address[1]}, {data}"
                )
            print(f"Received from {address[0]}:{address[1]}: {data.decode()}")

    def close(self):
        # 关闭套接字
        self.s.close()
